/**
 * @Date 2023-02-24 13:46:57
 * @Remark
 */

// react
import React, { useEffect } from "react";
// lib
import { Modal, Form, Input, Select } from "antd";
// components & widget
// config
import { MODULE_NAME } from "./config";
import { MODAL_STYLE } from "project/config";
import { INPUT_REQUIRED_RULE } from "project/validRules";
// store
import { observer } from "mobx-react";
import { state } from "./state";
// controller
import {
  addCategory,
  getCategoryLongPage,
  updateCategory,
} from "./controller";

function EditModal() {
  const [form] = Form.useForm();
  const show = state.editModalShow;
  const info = state.editInfo;
  const title = `${state.editInfo ? "编辑" : "新增"}${MODULE_NAME}`;

  const handleCancel = () => {
    state.editModal = false;
  };

  const handleOk = async () => {
    const result = await form.validateFields();
    if (info) {
      updateCategory(result, info.categoryId);
    } else {
      addCategory(result);
    }
  };

 
  useEffect(() => {
    if (show) {
      form.resetFields();
      getCategoryLongPage();
    }
    if (info) {
      form.setFieldsValue({
        ...info,
        parentCategory: info.parentCategoryId === 0 ? null : info.parentCategoryId,
      });
    }
    return () => {
      form.resetFields();
    };
  }, [form, show, info]);

  return (
    <Modal
      title={title}
      open={show}
      onCancel={handleCancel}
      onOk={handleOk}
      destroyOnClose
      maskClosable
      forceRender
      okButtonProps={{
        loading: state.editModalLoading,
      }}
    >
      <Form {...MODAL_STYLE.FORM_6_15} form={form}>
        <Form.Item name="parentCategoryId" label="上级分类">
          <Select
            placeholder="请选择一级分类"
            allowClear
          >
            {state.getLongList().map((item) => (
              <Select.Option key={item.categoryId} value={item.categoryId}>
                {item.categoryName}
              </Select.Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item name="categoryName" label="分类名称" rules={[INPUT_REQUIRED_RULE]}>
          <Input />
        </Form.Item>
      </Form>
    </Modal>
  );
}

export default observer(EditModal);
